<template>
  <view class="idea-edit-container">
    <!-- 内容编辑区 -->
    <view class="content-container">
      <!-- 标题输入 -->
      <input 
        class="title-input"
        v-model="formData.title"
        placeholder="输入标题（必填）"
        maxlength="50"
      />

      <!-- 自定义富文本编辑器 -->
      <IdeaEditor
        ref="editor"
        :initial-content="formData.content"
        :initial-images="formData.images"
        @change="handleEditorChange"
      />

      <!-- 子项目列表 -->
      <view class="sub-list-section">
        <view class="section-header">
          <text class="section-title">子项目</text>
          <view class="add-btn" @click="openSubItemDialog">
            <uni-icons type="plus" size="20" color="#2775b6"></uni-icons>
          </view>
        </view>
        
        <view 
          v-for="(item, index) in formData.subItems"
          :key="item.id"
          class="sub-item-card"
        >
          <text class="sub-item-text">{{ item.text }}</text>
          <uni-icons 
            type="trash" 
            size="20" 
            color="#EE3F4D"
            @click="removeSubItem(index)"
          ></uni-icons>
        </view>

        <view v-if="formData.subItems.length === 0" class="empty-tip">
          <uni-icons type="info" size="20" color="#999"></uni-icons>
          <text>点击添加按钮创建子项目</text>
        </view>
      </view>
    </view>

    <!-- 底部保存按钮 -->
    <view class="footer">
      <button class="save-btn" @click="handleSave">保存记录</button>
    </view>

    <!-- 添加子项目弹窗 -->
    <uni-popup ref="subItemDialog" type="dialog">
      <uni-popup-dialog 
        mode="input"
        title="添加子项目"
        placeholder="输入子项目内容"
        :maxlength="200"
        @confirm="addSubItem"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useCognitionStore } from '@/stores/cognitionStore'
import IdeaEditor from '@/components/cognition/IdeaEditor.vue'

const cognitionStore = useCognitionStore()
const editor = ref(null)
const subItemDialog = ref(null)

const formData = ref({
  id: '',
  title: '',
  content: '',
  images: [],
  subItems: [],
  updatedAt: ''
})

// 加载数据
onLoad((query) => {
  if (query.id) {
    const record = cognitionStore.contents['想法'].find(item => item.id === query.id)
    if (record) {
      formData.value = {
        id: record.id,
        title: record.title,
        content: record.content || '',
        images: record.images || [],
        subItems: record.subItems || [],
        updatedAt: record.updatedAt || ''
      }
    }
  } else {
    formData.value.id = Date.now().toString()
  }
})

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 保存数据
const handleSave = async () => {
  if (!formData.value.title.trim()) {
    uni.showToast({ title: '请输入标题', icon: 'none' })
    return
  }

  // 获取编辑器内容
  const { content, images } = await editor.value.getContent()

  const recordData = {
    id: formData.value.id,
    title: formData.value.title.trim(),
    content: content,
    images: images,
    subItems: formData.value.subItems,
    updatedAt: new Date().toISOString()
  }

  if (cognitionStore.contents['想法'].some(item => item.id === recordData.id)) {
    cognitionStore.updateContent(recordData.id, recordData)
  } else {
    cognitionStore.addContent(recordData)
  }

  uni.showToast({ title: '保存成功' })
  setTimeout(handleBack, 1500)
}

// 编辑器内容变化
const handleEditorChange = ({ content, images }) => {
  formData.value.content = content
  formData.value.images = images
}

// 打开子项目弹窗
const openSubItemDialog = () => {
  subItemDialog.value?.open()
}

// 添加子项目
const addSubItem = (text) => {
  if (!text || !text.trim()) return
  
  const newItem = {
    id: Date.now().toString(),
    text: text.trim(),
    createdAt: new Date().toISOString()
  }
  
  if (!formData.value.subItems) {
    formData.value.subItems = []
  }
  
  formData.value.subItems.unshift(newItem)
  subItemDialog.value?.close()
}

// 删除子项目
const removeSubItem = (index) => {
  uni.showModal({
    title: '删除子项目',
    content: '确定删除这个子项目吗？',
    success: ({ confirm }) => {
      if (confirm) {
        formData.value.subItems.splice(index, 1)
      }
    }
  })
}
</script>

<style scoped>
.idea-edit-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5fbfe;
  display: flex;
  flex-direction: column;
}

.content-container {
  flex: 1;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(135, 206, 235, 0.1);
  margin-bottom: 20rpx;
}

.title-input {
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  border: 1rpx solid rgba(135, 206, 235, 0.3);
}

.sub-list-section {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 1rpx dashed rgba(135, 206, 235, 0.5);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #2775b6;
}

.add-btn {
  padding: 8rpx;
  border-radius: 50%;
  background-color: rgba(39, 117, 182, 0.1);
}

.sub-item-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  margin-bottom: 16rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  border-left: 4rpx solid #87CEEB;
}

.sub-item-text {
  font-size: 28rpx;
  flex: 1;
  color: #333;
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  color: #999;
  font-size: 26rpx;
  gap: 10rpx;
}

.footer {
  padding: 20rpx;
  background-color: white;
  border-radius: 16rpx;
  box-shadow: 0 -2rpx 8rpx rgba(135, 206, 235, 0.1);
}

.save-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #2775b6;
  color: white;
  font-size: 30rpx;
  border-radius: 12rpx;
  border: none;
}

.save-btn:active {
  background-color: #1a5c96;
}
</style>